<script setup>
import { ref, toRefs } from 'vue'

const props = defineProps({
  settings: Array
})

const emit = defineEmits(['reload'])

let { settings } = toRefs(props)
let query = ref({})

const loadQuerySetting = () => {
  if (!props.settings || !props.settings.length) return
  props.settings.forEach(item => {
    if ('default' in item && item.default !== false) {
      query.value[item.field] = item.default
    } else {
      delete query.value[item.field]
    }
  })
}
loadQuerySetting()

const searchQuery = () => {
  emit('reload', query.value)
}

const searchReload = () => {
  loadQuerySetting()
  searchQuery()
}
</script>

<template>
  <a-form :layout="'inline'" :model="query">
    <a-form-item v-for="(item, idx) in settings" :key="idx">
      {{ void (width = (item.width || 140) + 'px') }}
      <a-select
          v-model:value="query[item.field]"
          :placeholder="'请选择'+item.label"
          v-if="item.components === 'select'"
          :style="{width: width}">
        <a-select-option :value="val.value" v-for="(val, key) in item.options" :key="key">
          {{ val.label }}
        </a-select-option>
      </a-select>

      <a-input
          v-model:value="query[item.field]"
          :placeholder="'请输入'+item.label"
          v-if="item.components === 'input'"
          :style="{width: width}"
      />

      <a-date-picker v-model:value="query[item.field]" v-else-if="item.components === 'date'" v-bind="item.attr || {}" />
    </a-form-item>
    <a-form-item>
      <a-button type="primary" @click="searchQuery">搜索</a-button>
      <a-button style="margin-left: 10px" @click="searchReload">重置</a-button>
    </a-form-item>
  </a-form>
</template>
